import styles from './index.module.scss'
import { NavBar, Form, Input, List, Button } from 'antd-mobile'
import { useHistory, useLocation } from 'react-router-dom'
import { LoginType } from '@/types/data'
import { useDispatch } from 'react-redux'
import { getCode, login } from '@/store/actions/login'
import { Toast } from 'antd-mobile'
import { useEffect, useRef, useState } from 'react'
import { FormInstance } from 'antd-mobile/es/components/form'
import { InputRef } from 'antd-mobile/es/components/input'

export default function Login() {
  const timerRef = useRef(-1)
  const history = useHistory()
  const dispatch = useDispatch()
  const formRef = useRef<FormInstance>(null)
  const inputRef = useRef<InputRef>(null)
  const mobileRef = useRef<InputRef>(null)
  const location = useLocation<{ from: string }>()
  const onFinish = async (values: LoginType) => {
    await dispatch(login(values))
    const from = location.state ? location.state.from : '/home'
    Toast.show({
      icon: 'success',
      content: '登錄成功',
    })
    history.replace(from)
  }
  //發送驗證碼按鈕的狀態
  const [time, setTime] = useState(0)

  //點擊獲取驗證碼按鈕
  const onGetCode = async () => {
    //如果時間大於0那麼不許重新發送驗證碼申請
    if (time > 0) return
    //拿到手機號碼
    const current = formRef.current! //current 一定有
    const mobile = current.getFieldValue('mobile')
    const error = current.getFieldError('mobile')
    //讓驗證碼框獲取焦點
    if (!mobile || error?.length > 0) {
      //當手機號為空時或者校驗提示的長度大於0是 讓手機號自動獲取焦點並ruturn掉
      mobileRef.current!.focus()
      return
    }
    await dispatch(getCode(mobile)) //await 驗證碼發了之後才開始倒計時
    //開啟倒計時
    setTime(60)
    timerRef.current = window.setInterval(() => {
      setTime(time => {
        return time - 1
      })
    }, 1000)
  }

  //清除定時器
  useEffect(() => {
    if (time === 0) {
      window.clearInterval(timerRef.current)
    }
  }, [time])
  //組件銷毀的時候清理定時器 這裡只做一件事就是清理副作用u
  useEffect(() => {
    return () => {
      window.clearInterval(timerRef.current)
    }
  }, [])
  return (
    <div className={styles.root}>
      <NavBar onBack={() => history.go(-1)}></NavBar>
      <div className='login-form'>
        <h2 className='title'>賬號登錄</h2>
        <Form
          ref={formRef}
          autoComplete='off' //提醒取消
          validateTrigger={['onChange', 'onBlur']} //觸發的時機
          onFinish={onFinish}
          initialValues={{
            mobile: '13911111111',
            code: '246810',
          }}>
          <Form.Item
            className='login-item'
            name='mobile'
            rules={[
              {
                required: true,
                message: '手機號不能為空',
              },
              {
                pattern: /^1[3-9]\d{9}$/,
                message: '手機號格式錯誤',
              },
            ]}>
            <Input placeholder='请手機號' maxLength={11} ref={mobileRef}></Input>
          </Form.Item>
          <List.Item
            className='login-code-extra'
            extra={
              <span className='code-extra' onClick={onGetCode}>
                {time === 0 ? '發送驗證碼' : `${time}秒後發送`}
              </span>
            }>
            <Form.Item
              className='login-item'
              name='code'
              rules={[
                {
                  required: true,
                  message: '驗證碼不能為空',
                },
                {
                  pattern: /^\d{6}$/,
                  message: '驗證碼格式錯誤',
                },
              ]}>
              <Input ref={inputRef} placeholder='請輸入驗證碼' maxLength={6}></Input>
            </Form.Item>
          </List.Item>
          <Form.Item>
            <Button color='primary' block className='login-submit' type='submit'>
              登錄
            </Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  )
}
